<template>
  <div class="step2">
    <!-- 提示框 -->
    <div class="select">
      <!-- <h2>{{ $t('reserve.browseAvailability') }}</h2> -->
      <p>{{ $t("reserve.selectDate") }}</p>
    </div>
    <!-- 日期选择框 -->
    <div class="fl-row date" dir="ltr">
      <el-date-picker
        v-model="value1"
        type="date"
        value-format="YYYY-MM-DD"
        :prefix-icon="customPrefix"
        popper-class="test"
        :format="dataFormat"
        @change="getData"
        :editable="false"
      />
      <span class="week-text" v-if="dataFormat.indexOf('1970') === -1">{{
        week
      }}</span>
    </div>
    <div class="fl-row page">
      <div class="date-but" @click="changDate(1)">
        <el-icon> <Back /> </el-icon>{{ $t("reserve.previous") }}
      </div>
      <div class="date-but" @click="changDate(2)">
        {{ $t("reserve.today") }}
      </div>
      <div class="date-but" @click="changDate(3)">
        <el-icon> <Right /> </el-icon>{{ $t("reserve.next") }}
      </div>
    </div>
    <!-- table -->
    <div class="table">
      <div
        class="common-pd-border today-text"
        v-if="dataFormat.indexOf('1970') === -1"
      >
        {{ tableTime === "" ? week + dataFormat : tableTime }}
      </div>
      <!-- 列表循环 -->
      <div v-for="(item, index) in list" :key="index" @click="choseId = index">
        <div class="list common-pd-border">
          <div class="list-left">
            <div>
              <!-- 时间 -->
              <div class="time">{{ item.time }}</div>
              <!-- <div class="time-dec">{{ item.time }}</div> -->
            </div>
            <!-- 名称 -->
            <!-- <div class="fl-row">
                <div>{{ store.store_name }}</div>
              </div> -->
          </div>
          <div class="list-right">
            <!-- 库存 -->
            <!-- <div>
                <div class="available">{{ $t("reserve.available") }}</div>
                <div class="count">{{ item.available }}</div>
              </div> -->
            <!-- 按钮 -->
            <div
              class="but"
              :class="{
                noIn: item.available == 0,
                active:
                  dateData.some((ite) => ite.index === item.index) &&
                  item.available !== 0,
              }"
              @click="onSelect(item)"
            >
              {{
                item.available > 0
                  ? $t("reserve.select")
                  : $t("reserve.soldOut")
              }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="fl-row bottom">
      <div class="date-but" @click="scrollIntoView">
        {{ $t("reserve.toTop") }}
      </div>
      <div class="fl-row">
        <div class="date-but" @click="changDate(1)">
          <el-icon> <Back /> </el-icon>{{ $t("reserve.previous") }}
        </div>
        <div class="date-but" @click="changDate(2)">
          {{ $t("reserve.today") }}
        </div>
        <div class="date-but" @click="changDate(3)">
          <el-icon> <Right /> </el-icon>{{ $t("reserve.next") }}
        </div>
      </div>
    </div>
    <div class="fl-row-but">
      <div class="but" @click="prevent">{{ $t("reserve.previous") }}</div>
      <div class="but" @click="next">{{ $t("reserve.next") }}</div>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { ElMessageBox } from "element-plus";
import { gameBookList } from "../reserve.service";
import { computed, h, ref, shallowRef, defineExpose } from "vue";
import moment from "moment";
import { useI18n } from "vue-i18n";

const dateData = ref([]);
const props = defineProps(["goodsId"]);
const store = JSON.parse(localStorage.getItem("store"));
const custom = JSON.parse(localStorage.getItem("custom") as any);
const { t } = useI18n();
const today = `${new Date().getFullYear()}-${
  // 今天
  new Date().getMonth() + 1 < 10
    ? "0" + (new Date().getMonth() + 1)
    : new Date().getMonth() + 1
}-${
  new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate()
}`;
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const tomorrowStr = `${tomorrow.getFullYear()}-${
  // 明天
  tomorrow.getMonth() + 1 < 10
    ? "0" + (tomorrow.getMonth() + 1)
    : tomorrow.getMonth() + 1
}-${tomorrow.getDate()}`;
const emits = defineEmits(["next", "prevent"]);
const value1 = ref(moment().format("YYYY-MM-DD"));
const week = ref("");
const month = ref(null);
const day = ref(null);
const dataFormat = computed(() => {
  // 时间选择器的显示formdata
  const date = new Date(value1.value);
  const weekDay = date.getDay(); // 返回值是 0（周日）到 6（周六）
  const arr = t("reserve.week").split(",");
  console.log(t("reserve.week"), "$t('reserve.next')");
  // 获取月份（0表示1月，11表示12月）
  month.value = date.getMonth() + 1; // 加1因为getMonth()返回的是从0开始的月份数字
  // 获取日（1-31）
  day.value = date.getDate();
  // 获取年份
  const year = date.getFullYear();
  week.value = arr[weekDay];
  console.log(week.value, "week");

  return "            " + month.value + " " + day.value + "," + " " + year;
});
const tableTime = computed(() => {
  // 时间计算
  if (value1.value == today) {
    return t("reserve.today");
  } else if (value1.value == tomorrowStr) {
    return t("reserve.today");
  }
  return "";
});

const customPrefix = shallowRef({
  // 日期前缀不要啦
  render() {
    return h("span", "");
  },
});
const list = ref([]); // 列表数据
const goodsInfo = ref([]);
const pushMoney = ref("");

const onSelect = (item: Object) => {
  for (let i = 0; i < dateData.value.length; i++) {
    if (dateData.value[i].index === item.index) {
      dateData.value.splice(i, 1);
      return;
    }
  }
  dateData.value.push(item);
};

// 获取列表数据
const getData = () => {
  dateData.value = []
  gameBookList({ date: value1.value, goods_id: props.goodsId }).then((res) => {
    list.value = res.data.book_list.map((item, index) => {
      item.index = index;
      return item;
    });
  });
};

// 下一步
const next = () => {
  console.log(dateData.value,"dateData.value");
  
  if (dateData.value.length && areIndicesConsecutive(dateData.value)) {
    let obj: Object = {
      date: dateData.value[0].date.replace(/-/g, ""),
      time: [],
    };
    dateData.value.forEach((item) => {
      obj.time.push(item.time);
    });
    emits("next", obj);
  } else {
    ElMessageBox.alert(t("reserve.timeHint"), {
      confirmButtonText: "OK",
      type: "warning",
      center: true,
      callback: (action: Action) => {},
    });
    console.log(2);
  }
};

const areIndicesConsecutive = (arr: Array<Object>) => {
  // 按 index 排序数组（如果已经排序则可以省略此步骤）
  arr.sort((a, b) => a.index - b.index);

  // 检查相邻对象的 index 是否相差为 1
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i + 1].index - arr[i].index !== 1) {
      return false;
    }
  }

  return true;
};

// 时间控制器
const changDate = (num: Number) => {
  console.log(num, today, "today");
  let last = "";
  let date = new Date(value1.value);
  console.log(value1.value);
  if (num === 1 && value1.value != today) {
    date.setDate(date.getDate() - 1); // 减一天
    last = `${date.getFullYear()}-${
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1
    }-${date.getDate() < 10 ? "0" + date.getDate() : date.getDate()}`;
  } else if (num === 3) {
    date.setDate(date.getDate() + 1); // 加一天
    last = `${date.getFullYear()}-${
      // 明天
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1
    }-${date.getDate() < 10 ? "0" + date.getDate() : date.getDate()}`;
  } else {
    last = today;
  }
  value1.value = last;
  getData();
  console.log(value1.value, "value1");
};
//平滑滚动顶部
const scrollIntoView = () => {
  window.scrollTo({
    top: 0,
    left: 0,
    behavior: "smooth",
  });
};

const prevent = () => {
  emits("prevent");
};

defineExpose({ getData });
</script>
  
  <style scoped lang="scss">
.step2 {
  .select {
    text-align: left;
    color: #0e2e57;
    margin-bottom: 5px;
    margin-left: 8px;

    h2 {
      margin-bottom: 5px;
      font-size: 18px;
      line-height: 1.4;
      font-weight: 600;
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }

  .fl-row {
    display: flex;
    justify-content: space-between;
    position: relative;
  }

  .page {
    justify-content: left;
    margin-left: 10px;
    margin-bottom: 10px;
  }

  .date {
    margin-left: 8px;
    margin-bottom: 30px;
  }

  .date-but {
    border-radius: 0;
    border-top-left-radius: 3px;
    border-bottom-left-radius: 3px;
    margin-right: -1px;
    border: 1px solid var(--theme-color);
    font-size: 12px;
    padding: 10px 13px;
    color: #0e2e57;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;

    .el-icon {
      font-size: 18px;
      margin-right: 4px;
    }
  }

  .table {
    width: 100%;
    text-align: left;
    .today-text {
      margin-left: 8px;
    }
    .common-pd-border {
      border-bottom: 1px solid var(--theme-color);
      padding-bottom: 15px;
      color: #0e2e57;
      font-weight: 600;
    }

    .list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      margin: 0 15px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;

      .list-left {
        width: 70%;
        display: flex;
        align-items: center;
        margin-right: 10px;

        .time {
          font-size: 14px;
          margin-right: 20px;
          text-align: center;
        }

        .fl-row {
          max-width: 90px;
          font-size: 14px;
        }

        .time-dec {
          margin: 4px 0;
          font-size: 12px;
          margin-right: 20px;
          text-align: center;
        }
      }

      .list-right {
        display: flex;
        align-items: center;
        flex: 1;

        .available {
          margin-bottom: 4px;
          font-size: 12px;
        }

        .count {
          font-size: 18px;
          letter-spacing: -1.2px;
          text-align: center;
        }

        .but {
          width: 100%;
          color: #e2e8fc;
          background: var(--theme-color-btn);
          font-size: 12px;
          text-align: center;
          cursor: pointer;
        }
        .noIn {
          background: #ccc;
          color: #333;
          cursor: not-allowed;
        }
        .active {
          background: var(--theme-color);
          color: #fff;
        }
      }
    }

    .chose-list {
      padding: 20px 0;
      border-bottom: 1px solid var(--theme-color);

      .left {
        color: #e2e8fc;
        background: var(--theme-color-btn);
        width: 50px;
        height: 50px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 10px;
        .month {
          font-size: 16px;
        }
      }

      .right {
        text-align: left;
        width: 85%;

        .title {
          font-size: 16px;
          margin-bottom: 10px;
        }

        .close {
          margin: auto 0 auto auto;
          display: block;
          font-size: 18px;
          font-size: 30px;
          cursor: pointer;
        }

        .num-money {
          display: flex;
          align-items: center;
          margin-top: 40px;
          padding-bottom: 20px;
          border-bottom: 1px solid var(--theme-color);

          .money {
            margin-right: 50px;
            font-size: 14px;
            color: #0e2e57;
            font-weight: 600;
            .dan {
              margin-left: 5px;
            }
          }

          .el-input-number {
            width: 100px;
            height: 40px;
            margin-left: auto;
          }

          :deep(.el-input-number__decrease) {
            width: 30px;
            height: 30px;
            background: transparent;
            border-right: 1px solid var(--theme-color);
            top: 4px;
          }

          :deep(.el-input-number__increase) {
            width: 30px;
            height: 30px;
            background: transparent;
            border-left: 1px solid var(--theme-color);
            top: 4px;
          }

          :deep(.el-input__wrapper) {
            height: 30px;
            padding-left: 30px;
          }
        }

        .playlist {
          padding-left: 10px;
          margin-top: 10px;
          .list-item {
            margin-bottom: 10px;
            .line {
              display: flex;
              align-items: center;
              img {
                width: 40px;
              height: 40px;
              margin-right: 10px;
              }
              .title {
                flex: 1;
              font-weight: bold;
              font-size: 12px;
              margin-bottom: 0;
              }
              .num-money {
      
                margin-right: 5px;
                margin-top: 0;
                padding: 0;
                border: none;
                .money {
                  display: flex;
                flex-direction: column;
                font-size: 10px;
                margin-right: 10px;
                margin-left: 5px;
                max-width: 90px;
                }
              }
              .el-icon {
                font-size: 16px;
              margin-right: 10px;
              cursor: pointer;
              color: rgb(64, 118, 192);
              }
            }
            .detail {
              margin-top: 10px;
              .title {
              font-size: 18px;
            }
            }
          }
        }

        .money-all {
          display: flex;
        align-items: center;
        padding-bottom: 10px;
        padding: 10px 10px;
        justify-content: space-between;

        .money {
          margin-right: 50px;
          font-size: 12px;
          font-weight: 600;

          span {
            color: var(--theme-color);
          }

          .ft-20 {
            font-size: 20px;
          }
          .ft-21 {
            font-size: 16px;
          }
        }
        .money2 {
          font-size: 12px;
        }
          .but {
            color: #e2e8fc;
            background: var(--theme-color-btn);
            font-size: 14px;
            width: 50%;
            margin-left: 45px;
            text-align: center;
            height: 42px;
            line-height: 42px;
            font-weight: 600;
            cursor: pointer;
            &:hover {
              background: var(--theme-color);
              color: #fff;
            }
          }
        }
      }
    }
  }

  .bottom {
    margin-top: 40px;
  }
}

:deep(.el-input__wrapper) {
  padding: 0 30px 0 10px;
  font-size: 12px;
  font-weight: 600;
  height: 40px;
  color: #0e2e57;
  background: transparent;
  border: 1px solid var(--theme-color);
}
.week-text {
  line-height: 42px;
  font-size: 12px;
  position: absolute;
  left: 15px;
  color: #555;
}

.fl-row-but {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 30px;
  margin-top: 30px;
  margin-right: 10px;
}

.but {
  color: #e2e8fc;
  background: var(--theme-color-btn);
  font-size: 14px;
  width: 30%;
  //margin-left: 45px;
  text-align: center;
  cursor: pointer;
  height: 42px;
  line-height: 42px;
  //margin: 0 0 0 auto;
  font-weight: 600;
}

.ellipsis {
  white-space: nowrap; /* 保证文本在一行内显示 */
  overflow: hidden; /* 超出容器部分隐藏 */
  text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
}
</style>
  <style>
@import "./step1.scss";
</style>